#include <QDataStream>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <dirent.h>
#include "xio.h"

XIO::XIO(){}

bool XIO::getPaths(const QString& dirPath, QStringList& result, bool isDir) {
    result.clear();
    DIR* dir = opendir(dirPath.toStdString().c_str());
    if (!dir)
        return false;
    struct dirent* entry;
    while ((entry = readdir(dir)) != nullptr) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue;
        QString path = QString(dirPath.endsWith('/') ? "%1%2" : "%1/%2").arg(dirPath).arg(entry->d_name);
        if (isDir) {
            if (QFileInfo(path).isDir())
                result.push_back(path);
        } else {
            if (QFileInfo(path).isFile())
                result.push_back(path);
        }
    }
    closedir(dir);
    return true;
}

void XIO::getName(const QString& path, QString& result) {
    int idx = path.lastIndexOf('/');
    if (idx == -1) {
        result = path;
        return;
    }
    result = path.mid(idx + 1);
}

bool XIO::serializeQVector(const QStringList& src, const QString& savePath) {
    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly))
        return false;
    QDataStream out(&file);
    out << src;
    file.close();
    return true;
}

bool XIO::deserializeQVector(const QString& filePath, QStringList& dst) {
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly))
        return false;
    QDataStream in(&file);
    in >> dst;
    file.close();
    return true;
}

bool XIO::readText(const QString& filePath, QString& result, int head) {
    result.clear();
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;
    QTextStream in(&file);
    if (head == -1) {
        result = in.readAll();
    } else {
        for (int i = 0; i < head; ++ i) {
            QString line = in.readLine();
            if (line.isNull())
                break;
            result += line;
            if (i != head - 1)
                result += "\n";
        }
    }
    file.close();
    return true;
}

bool XIO::writeText(const QString& text, const QString& savePath, bool appendText) {
    QFile file(savePath);
    if (appendText) {
        if (!file.open(QIODevice::Append | QIODevice::Text))
            return false;
    } else {
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
            return false;
    }
    QTextStream out(&file);
    out << text;
    file.close();
    return true;
}
